package me.leiusual.sharing.ui.mine

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_mine_info.*
import me.leiusual.sharing.BuildConfig
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.*
import me.leiusual.sharing.util.tool.UriUtil
import timber.log.Timber
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/16
 */
class MineInfoFragment : DaggerFragment() {

  companion object {
    private const val CURRENT_PHOTO_PATH = "currentPhotoPath"

    private const val REQ_PHOTO_TAKE = 11
    private const val REQ_PHOTO_PICK = 12
  }

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: MineInfoViewModel by viewModels { factory }

  private var currentPhotoPath: String? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    if (savedInstanceState != null && savedInstanceState.containsKey(CURRENT_PHOTO_PATH)) {
      currentPhotoPath = savedInstanceState.getString(CURRENT_PHOTO_PATH)
    }
  }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_mine_info, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    text_view_item_avatar.setOnClickListener {
      startSelectImage()
    }

    text_view_nickname.setOnClickListener {
      findNavController().navigate(R.id.action_mineInfoFragment_to_mineNicknameFragment)
    }

    text_view_item_mobile.setOnClickListener {
      findNavController().navigate(R.id.action_mineInfoFragment_to_mineMobileFragment)
    }

    text_view_item_qr_code.setOnClickListener {
      findNavController().navigate(R.id.action_global_mineInviteFragment)
    }

    updateUserInfo()

    observeData()
  }

  override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putString(CURRENT_PHOTO_PATH, currentPhotoPath)
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    Timber.v("onActivityResult data = %s", data)

    if (requestCode == REQ_PHOTO_TAKE && resultCode == Activity.RESULT_OK) {
      viewModel.avatarUpdate(currentPhotoPath ?: return)
    }
    if (requestCode == REQ_PHOTO_PICK && resultCode == Activity.RESULT_OK) {
      currentPhotoPath = UriUtil.getPath(context, data?.data ?: return) ?: return
      viewModel.avatarUpdate(currentPhotoPath ?: return)
    }
  }

  private fun observeData() {
    viewModel.avatarUpdate.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("avatarUpdate = %s", it)
      when (it) {
        is Data.Loading -> {
          text_view_item_mobile.isEnabled = false
        }
        is Data.Error -> {
          text_view_item_mobile.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          text_view_item_mobile.isEnabled = true
          image_view_header.setImageUrl(it.data)
          toast("头像更新成功")
        }
      }
    })
  }

  private fun updateUserInfo() {
    image_view_header.setImageUrl(viewModel.user.avatar)
    text_view_nickname.text = viewModel.user.nickname
    text_view_phone.text = viewModel.user.mobile.toImplicitMobile()
    text_view_real_name.text = viewModel.user.realName.toImplicitRealName()
    text_view_id_card.text = viewModel.user.idCard.toImplicitIdCard()
    text_view_gender.text = "未知"
  }

  private fun startSelectImage() {
    context?.let {
      AlertDialog.Builder(it)
          .setItems(arrayOf("拍照", "相册", "取消")) { _, which ->
            when (which) {
              0 -> {
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                if (intent.resolveActivity(it.packageManager) != null) {
                  val photoFile = createImageFile(it) ?: return@setItems
                  val authority = BuildConfig.APPLICATION_ID + ".fileProvider"
                  val photoUri = FileProvider.getUriForFile(it, authority, photoFile)
                  intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
                  startActivityForResult(intent, REQ_PHOTO_TAKE)
                }
              }
              1 -> {
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.type = "image/*"
                if (intent.resolveActivity(it.packageManager) != null) {
                  startActivityForResult(intent, REQ_PHOTO_PICK)
                }
              }
            }
          }
          .show()
    }
  }

  private fun createImageFile(context: Context): File? {
    try {
      val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(Date())
      val imageFileName = "JPEG_${timeStamp}_"
      val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
      val image = File.createTempFile(imageFileName, ".jpg", storageDir)
      currentPhotoPath = image.absolutePath
      return image
    } catch (e: Throwable) {
      e.printStackTrace()
    }
    return null
  }
}